package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.bean.MeasurePoint;
import com.hengxinguotong.zhihuichengjian.bean.News;
import com.hengxinguotong.zhihuichengjian.database.NewsDAO;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by liux on 2017/4/22.
 */

public class WebViewActivity extends BaseActivity {
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.iv_detail)
    HXTextView ivDetail;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.progressbar)
    ProgressBar progressbar;
    @BindView(R.id.article_collect)
    HXTextView articleCollect;
    @BindView(R.id.back_layout)
    RelativeLayout backLayout;
    private boolean isArticle = false;
    private boolean isCollected = false;
    private String title;
    private ValueCallback<Uri> uploadUriMsg;
    private ValueCallback<Uri[]> uploadUrisMsg;
    private final static int FILECHOOSER_RESULTCODE = 1;// 表单的结果回调
    public final static int FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 = 2;
    private String currentUrl = null;
    private String origenUrl = null;
    private boolean isFirstLoad = true;
    private List<String> titles;
    private List<News> articleList;
    private News news;
    private NewsDAO service;
    private Map<String, Object> map;
    private MeasurePoint measurePoint;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        titles = new ArrayList<>();
        title = getIntent().getStringExtra("title");
        if("新闻资讯".equals(title)) {
            news = (News) getIntent().getSerializableExtra("news");
            service = new NewsDAO(this);
            newsFilter(news);
            origenUrl = news.getLink();
            isArticle = true;
            ivDetail.setText("收藏");
        } else if("关于我们".equals(title)) {
            origenUrl = getIntent().getStringExtra("url");
        } else if("扫一扫".equals(title)) {
            origenUrl = getIntent().getStringExtra("url");
        } else if("考勤管理".equals(title)) {
            origenUrl = Utils.getServerUrl(this)+getIntent().getStringExtra("url")  + "&appVersion=" + Utils.getVersionName(this);
            ivDetail.setText("查询");
//            if(hasList()){
//                ivDetail.setVisibility(View.VISIBLE);
//            }else{
                ivDetail.setVisibility(View.GONE);
//            }
        }else if("环境监测".equals(title)){
            origenUrl = Utils.getServerUrl(this)+getIntent().getStringExtra("url") + "&appVersion=" + Utils.getVersionName(this);
            ivDetail.setText("喷淋");
        } else if("检查标准".equals(title)){
            origenUrl = getIntent().getStringExtra("url");
            measurePoint = (MeasurePoint) getIntent().getSerializableExtra("measurePoint");
//            map = new HashMap<String, Object>();
//            map.put("assessQty", measurePoint.getAssessQty());
//            map.put("qualityStandard", measurePoint.getQualityStandard());
//            map.put("inspectionMethod", measurePoint.getInspectionMethod());
        } else if("advertisement".equals(title)){
            origenUrl = getIntent().getStringExtra("url");
        }else {
            origenUrl = Utils.getServerUrl(this)+getIntent().getStringExtra("url") + "&appVersion=" + Utils.getVersionName(this);
        }
        if("高支模".equals(title) || "高支模监测".equals(title) || "高支模设置".equals(title)){
            rlTitle.setVisibility(View.GONE);
        }
        if("二级菜单".equals(title) || "出勤登记".equals(title)){
            rlTitle.setVisibility(View.GONE);
        }
        titleTv.setText(title);
        titles.add(title);
        //支持javascript
        webview.getSettings().setJavaScriptEnabled(true);

        // 设置可以支持缩放
        webview.getSettings().setSupportZoom(true);
        // 设置出现缩放工具
        webview.getSettings().setBuiltInZoomControls(true);
        //扩大比例的缩放
        webview.getSettings().setUseWideViewPort(true);
        //自适应屏幕
        webview.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webview.getSettings().setLoadWithOverviewMode(true);
        webview.getSettings().setAppCacheEnabled(true);//是否启用缓存模式
        webview.getSettings().setDatabaseEnabled(true);//是否开启数据库缓存
        //设置 缓存模式
        webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        // 开启 DOM storage API 功能
        webview.getSettings().setDomStorageEnabled(true);
        webview.setWebViewClient(webViewClient);
        webview.setWebChromeClient(webChromeClient);
        webview.loadUrl(origenUrl);

        //在js中调用本地java方法，为防止网页还未加载完毕就调用方法导致无效，所以延迟1秒执行
//        new Handler().postDelayed(new Runnable(){
//            public void run() {
//                String num = Utils.getVersionName(WebViewActivity.this);
//                webview.loadUrl("javaScript:getVersion('"+num+"')");
//            }
//        }, 1000);


    }

    /**
     * 过滤已收藏文章
     *
     * @param
     */
    private void newsFilter(News news) {
        articleList = service.selectAll();
        Iterator<News> newsIterator = articleList.iterator();
        while (newsIterator.hasNext()) {
            News collectedNews = newsIterator.next();
            if(collectedNews.getId().equals(news.getId())){
                isCollected = true;
                articleCollect.setText("取消收藏");
                articleCollect.setBackgroundColor(getResources().getColor(R.color.color_F76C75));
                return;
            }else{
                isCollected = false;
                articleCollect.setText("收藏文章");
                articleCollect.setBackgroundColor(getResources().getColor(R.color.color_cbedff));
            }
        }
    }

    private class JsInterface{
        @JavascriptInterface
        public void setVersion() {
            String num = Utils.getVersionName(WebViewActivity.this);
            //调用js中的函数：getVersion(Num)
            webview.loadUrl("javaScript:getVersion('" + num + "')");
        }
    }

    @OnClick({R.id.iv_back, R.id.iv_detail, R.id.article_collect, R.id.back_layout})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
//                finish();
                goBackWeb();
                break;
            case R.id.iv_detail:
                if("环境监测".equals(title)){
                    Intent intent = new Intent(this, WebViewActivity.class);
                    String url = "/environment/toSpray/" + SPUtil.getString(this, "uuid") + "?constructionId=" + SPUtil.getString(this, "constructionid");
                    intent.putExtra("url", url);
                    startActivity(intent);
                } else {
                    if(isArticle){
                        articleCollect.setVisibility(View.VISIBLE);
                    }else{
                        Intent intent = new Intent(this, WebViewActivity.class);
                        String url = "/attendance/toAttendanceQuery/" + SPUtil.getString(this, "uuid") + "?constructionId=" + SPUtil.getString(this, "constructionid");
                        intent.putExtra("url", url);
//                title = "考勤查询";
//                intent.putExtra("title", title);
                        startActivity(intent);
                    }
                }

                break;
            case R.id.article_collect:
                if(isCollected){
                    isCollected = false;
                    articleCollect.setText("收藏文章");
                    articleCollect.setBackgroundColor(getResources().getColor(R.color.color_cbedff));
                    articleCollect.setVisibility(View.GONE);
                    service.delNews(news);
                }else{
                    isCollected = true;
                    articleCollect.setText("取消收藏");
                    articleCollect.setBackgroundColor(getResources().getColor(R.color.color_F76C75));
                    articleCollect.setVisibility(View.GONE);
                    service.addNews(news);
                }
                break;
            case R.id.back_layout:
                if(!webview.canGoBack()){
                    finish();
                }
                break;
        }
    }


    private void goBackWeb() {
        if (Utils.isEmpty(currentUrl)) {
            WebViewActivity.this.finish();
        } else if (!Utils.isEmpty(origenUrl) && !origenUrl.equals(currentUrl)) {
            titles.remove(titles.size()-1);
            titleTv.setText(titles.get(titles.size()-1));
            webview.goBack();
        } else if (!Utils.isEmpty(origenUrl) && origenUrl.equals(currentUrl)) {
            WebViewActivity.this.finish();
        }
    }

    private WebViewClient webViewClient = new WebViewClient() {

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            view.getSettings().setJavaScriptEnabled(true);
//            view.loadUrl(url);
//            return true;
            if (url.startsWith("mailto:") || url.startsWith("geo:") || url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
                return true;
            }
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            try {
                if (isFirstLoad) {
                    isFirstLoad = false;
                    currentUrl = null;
                } else {
                    currentUrl = url;
                }
            } catch (Exception e) {

            }
            if("高支模".equals(title) || "高支模监测".equals(title) || "高支模设置".equals(title)){
                if(webview.canGoBack()){
                    backLayout.setVisibility(View.GONE);
                }else{
                    backLayout.setVisibility(View.VISIBLE);
                }
            }
            String num = Utils.getVersionName(WebViewActivity.this);
            if("关于我们".equals(title))
            webview.loadUrl("javaScript:getVersion('"+num+"')");
            if("检查标准".equals(title)){
                String map = measurePoint.getAssessQty() + "$" + measurePoint.getInspectionMethod() + "$" + measurePoint.getQualityStandard();
                webview.loadUrl("javaScript:setStandard('"+map+"')");
            }
        }
    };

    private WebChromeClient webChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                // 网页加载完成
                progressbar.setVisibility(View.GONE);
                if("高支模".equals(title) || "高支模监测".equals(title) || "高支模设置".equals(title)){
                    if(webview.canGoBack()){
                        backLayout.setVisibility(View.GONE);
                    }else{
                        backLayout.setVisibility(View.VISIBLE);
                    }
                }
                String num = Utils.getVersionName(WebViewActivity.this);
                if("关于我们".equals(title))
                    webview.loadUrl("javaScript:getVersion('"+num+"')");
                if("检查标准".equals(title)){
                    String map = measurePoint.getAssessQty() + "$" + measurePoint.getInspectionMethod() + "$" + measurePoint.getQualityStandard();
                    webview.loadUrl("javaScript:setStandard('"+map+"')");
                }
            } else {
                // 加载中
                progressbar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            titleTv.setText(title);
            titles.add(title);
        }

        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
            uploadUriMsg = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
        }

        // For Android 3.0+
        public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
            uploadUriMsg = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("*/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "File Browser"), FILECHOOSER_RESULTCODE);
        }

        // For Android 4.1
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            uploadUriMsg = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);

        }

        // for Android 5.0
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            uploadUrisMsg = filePathCallback;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 );
            return true;
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        Uri result = (intent == null || resultCode != RESULT_OK) ? null: intent.getData();
        switch (requestCode){
            case FILECHOOSER_RESULTCODE:  //android 5.0以下 选择图片回调

                if (null == uploadUriMsg)
                    return;
                uploadUriMsg.onReceiveValue(result);
                uploadUriMsg = null;

                break;

            case FILE_CHOOSER_RESULT_CODE_FOR_ANDROID_5 :  //android 5.0(含) 以上 选择图片回调

                if (null == uploadUrisMsg)
                    return;
                if (result != null) {
                    uploadUrisMsg.onReceiveValue(new Uri[]{result});
                } else {
                    uploadUrisMsg.onReceiveValue(new Uri[]{});
                }
                uploadUrisMsg = null;

                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        clearCach();
    }

    private void clearCach(){
        webview.clearCache(true);
//        webview.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        deleteDatabase("WebView.db");
        deleteDatabase("WebViewCache.db");
        webview.clearHistory();
        webview.clearFormData();
        getCacheDir().delete();
    }

    //    private void attendanceSearch(String alert){
//        JSONObject jsonObject = new JSONObject();
//
//        try {
//            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        RequestParams params = new RequestParams();
//        params.addHeader("Content-type", "application/json");
//        try {
//            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        Utils.requestData(alert, this, "/attendance/toAttendanceQuery/" + SPUtil.getString(this, "uuid") + "?constructionid=" + SPUtil.getString(this, "constructionid") , null, new Utils.ListenerJson() {
//            @Override
//            public void onSuccess(String json) {
//                showToast(json);
//            }
//
//            @Override
//            public void onFailure(String json) {
//                showToast(json);
//            }
//        });
//    }

}
